package com.example.night.service.ApiService;

import com.example.night.data.InfluencerCoins.WithdrawRecord;
import com.example.night.data.InfluencerCoins.WithdrawRecord.WithdrawStatus;
import com.example.night.service.MysqlService.WithdrawRecordMysqlService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class WithdrawRecordService {

    private final WithdrawRecordMysqlService withdrawRecordMysqlService;

    // **存储提现记录的列表**
    private final List<WithdrawRecord> withdrawRecords = new ArrayList<>();

    public WithdrawRecordService(WithdrawRecordMysqlService withdrawRecordMysqlService) {
        this.withdrawRecordMysqlService = withdrawRecordMysqlService;
        loadWithdrawRecordsFromDatabase(); // 启动时加载数据
    }

    /**
     * 从数据库加载提现记录到列表
     */
    public void loadWithdrawRecordsFromDatabase() {
        try {
            List<WithdrawRecord> records = withdrawRecordMysqlService.getAllWithdrawRecords();
            withdrawRecords.clear();
            withdrawRecords.addAll(records);
            log.info("成功从数据库加载 {} 条提现记录", records.size());
        } catch (Exception e) {
            log.error("从数据库加载提现记录失败", e);
        }
    }

    public WithdrawRecord addWithdrawRequest(String promoteId, String promoteName, int withdrawCoins) {
        if (withdrawCoins <= 0) {
            log.warn("提现申请失败：提现金额必须大于0，promoteId={}，withdrawCoins={}", promoteId, withdrawCoins);
            return null;
        }

        WithdrawRecord newRecord = new WithdrawRecord();
        newRecord.setPromoteId(promoteId);
        newRecord.setPromoteName(promoteName);
        newRecord.setWithdrawCoins(withdrawCoins);
        newRecord.setWithdrawAmount(BigDecimal.ZERO); // 可根据汇率计算
        newRecord.setStatus(WithdrawRecord.WithdrawStatus.PENDING);
        newRecord.setApplyTime(LocalDateTime.now());

        try {
            WithdrawRecord savedRecord = withdrawRecordMysqlService.addWithdrawRecord(newRecord);
            if (savedRecord != null) {
                withdrawRecords.add(savedRecord); // 更新本地列表
                log.info("成功添加提现申请：{}", savedRecord);
            }
            return savedRecord;
        } catch (Exception e) {
            log.error("提现申请失败", e);
            return null;
        }
    }

    /**
     * 获取所有提现记录
     */
    public List<WithdrawRecord> getAllWithdrawRecords() {
        return new ArrayList<>(withdrawRecords);
    }

    /**
     * 根据提现状态查询记录
     */
    public List<WithdrawRecord> getWithdrawRecordsByStatus(WithdrawStatus status) {
        return withdrawRecords.stream()
                .filter(record -> record.getStatus() == status)
                .collect(Collectors.toList());
    }
}
